package com.xiaoma.mframe.project.tool.gen.controller;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xiaoma.mframe.general.web.controller.BaseController;
import com.xiaoma.mframe.general.web.page.TableDataInfo;
import com.xiaoma.mframe.project.tool.gen.entity.TableInfo;
import com.xiaoma.mframe.project.tool.gen.service.IGenService;

/**
 * 代码生成 操作处理
 * 
 * @author xiaoma
 */
@Controller
@RequestMapping("/tool")
public class GenController extends BaseController {
	private String prefix = "tool/gen";

	@Autowired
	private IGenService genService;

	@GetMapping()
	public String gen() {
		return prefix + "/gen";
	}

	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(TableInfo tableInfo) {
		startPage();
		List<TableInfo> list = genService.selectTableList(tableInfo);
		return getDataTable(list);
	}

	/**
	 * 生成代码
	 */
	@GetMapping("/genCode/{tableName}")
	public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
		byte[] data = genService.generatorCode(tableName);
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"auto.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IOUtils.write(data, response.getOutputStream());
	}
	/**
	 * 批量生成代码
	 */
	@GetMapping("/batchGenCode/{tableNames}")
	public void batchGenCode(HttpServletResponse response, @PathVariable("tableNames") String tableNames) throws IOException {
		String [] s = tableNames.split(",");

		for (String tableName : s) {
			byte[] data = genService.generatorCode(tableName);	
			response.reset();
			response.setHeader("Content-Disposition", "attachment; filename=\""+tableName+".zip\"");
			response.addHeader("Content-Length", "" + data.length);
			response.setContentType("application/octet-stream; charset=UTF-8");

			IOUtils.write(data, response.getOutputStream());
		}
		
		
	}
}
